package com.adams.role.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.adams.access.db.bean.Role;
import com.adams.access.db.bean.User;
import com.adams.access.db.bean.ViewEvent;
import com.adams.encache.mechanism.CacheUtil;
import com.adams.role.dao.RoleDao;
import com.adams.role.service.RoleService;
import com.adams.user.dao.UserDao;
import com.adams.utils.Page;

/**
 * 
 * 
 * File Name : RoleServiceImpl.java
 * 
 * @Description : 角色管理服务类，提供对角色的增、删、改查功能
 * @author 902990封文进
 */
@Service("roleService")
@Transactional
public class RoleServiceImpl implements RoleService
{

	@Autowired
	private RoleDao roleDao;

	@Autowired
	private UserDao userDao;

	public void setUserDao(UserDao userDao)
	{
		this.userDao = userDao;
	}

	public void setRoleDao(RoleDao roleDao)
	{
		this.roleDao = roleDao;
	}

	/**
	 * 
	 * Description : 创建角色
	 * 
	 * @param role
	 * 
	 */
	@Transactional(rollbackFor = java.lang.Exception.class)
	public void createRole(Role role)
	{
		role.setVersion(1);
		roleDao.save(role);
		CacheUtil.clearCacheByClass(Role.class);
	}

	/**
	 * 
	 * Description : 更新角色
	 * 
	 * @param role
	 * 
	 */
	@Transactional(rollbackFor = java.lang.Exception.class)
	public void updateRole(Role role)
	{
		roleDao.update(role);
		CacheUtil.clearCacheByClass(Role.class);
	}

	/**
	 * 
	 * Description : 删除角色
	 * 
	 * @param role
	 * 
	 */
	@Transactional(rollbackFor = java.lang.Exception.class)
	public void deleteRole(Role role)
	{
		List<User> list = userDao.queryByRoleId(role.getId());
		for (User user : list)
		{
			user.setRole(null);
			userDao.update(user);
		}
		roleDao.delete(role);
		CacheUtil.clearCacheByClass(Role.class);
	}

	/**
	 * 
	 * Description : 根据编号查询角色
	 * 
	 * @param id
	 * @return Role
	 * 
	 */
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public Role queryById(Long id)
	{
		return roleDao.get(id);
	}

	/**
	 * 
	 * Description : 根据名称查询角色
	 * 
	 * @param name
	 * @return Role
	 * 
	 */
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public Role queryByName(String name)
	{
		return roleDao.queryByName(name);
	}

	/**
	 * 
	 * Description : 根据分页查询角色
	 * 
	 * @param page
	 * @return Page<Role>
	 * 
	 */
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public Page<Role> queryAllByPage(Page<Role> page)
	{
		return roleDao.queryAllByPage(page);
	}

}
